﻿using System.Linq;
using System.Web.Mvc;

using Kooboo.Web.Models;
using Kooboo.Web.Mvc.Paging;
using Kooboo.Commerce.Contexts.Categories;
using Kooboo.Web.Mvc;


namespace Kooboo.Web.Controllers
{
    using Kooboo.Commerce;
    using Kooboo.Commerce.Services;

    public class CategoryController : ControllerBase
    {
        //
        // GET: /Category/

        public ActionResult Index(int id, int? page, string sort)
        {
            this.BindViewData();

            BindData(id);

            ProductSortType sortType = ProductSortType.NameByAsc;

            switch (sort)
            {
                case "nameza":
                    sortType = ProductSortType.NameByDesc;
                    break;
                case "pricelh":
                    sortType = ProductSortType.PriceByAsc;
                    break;
                case "pricehl":
                    sortType = ProductSortType.PriceByDesc;
                    break;
                default:
                    sortType = ProductSortType.NameByAsc;
                    break;
            }

            var service = new ProductService();

            var products = service.GetProductsByCategoryId(id, sortType, page ?? 1, Configuration.PageSize)
                .Select(i => new
                {
                    Id = i.ProductId,
                    i.Name,
                    Price = i.Price.ToString("C"),
                    Image = combianThumbnailImageUrl(i.Thumbnail),
                    Url = this.Url.Action<ProductController>(m => m.View(i.ProductId, null))
                })
                .AsEnumerable();


            return View(products);
        }

        private ICategory BindData(int id)
        {
            var category = this.Actor.QueryCategories()
                .Where(i => i.Id == id).FirstOrDefault();

            this.Select(category);

            var list = category.Children.Select(i => new CategorySummary { Name = i.Name, Id = i.Id, Count = i.Products.Count() }).ToList();

            ViewData["Categories"] = list;
            return category;
        }

        private string combianThumbnailImageUrl(string thumbnailName)
        {
            if (!string.IsNullOrEmpty(thumbnailName))
            {
                return Kooboo.Commerce.Configuration.FindImageUrlBase(Kooboo.Commerce.Configuration.ProductImageFolder, "Thumnail") + thumbnailName;
            }
            else
            {
                return Configuration.ImageNotAvailable_Thumbnail;
            }
        }

        public ActionResult Search(string query)
        {
            return View();
        }
    }
}
